package com.chenwc.netty.tcp.client;

import com.alibaba.fastjson.JSONObject;
import com.chenwc.netty.tcp.coder.Message;
import com.chenwc.netty.tcp.config.NettyProperties;
import com.chenwc.netty.tcp.enums.MessageEnum;
import com.chenwc.netty.tcp.task.KeepAliveTask;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class LongConnectionClient {
    private static final Logger log = LoggerFactory.getLogger(LongConnectionClient.class);
    private static final String EP_ID = UUID.randomUUID().toString().replace("-", "");
    private static final NettyProperties nettyProperties = new NettyProperties();

    public static void main(String[] args) {

        Socket client = null;
        OutputStream os = null;
        InputStream is = null;
        DataOutputStream dos = null;
        DataInputStream dis = null;
        try {
            client = new Socket(InetAddress.getByName("localhost"), 9877);
            log.info("---长连接客户端---");

            os = client.getOutputStream();
            dos = new DataOutputStream(os);
            manualKeepAlive(dos);
            while (true) {
                is = client.getInputStream();
                dis = new DataInputStream(is);
                int length = dis.available();
                if (length > 0) {
                    byte[] result = new byte[length];
                    dis.read(result);
                    String strtmp = new String(result, StandardCharsets.UTF_8);
                    handleMessage(strtmp);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                IOUtils.closeQuietly(is);
                IOUtils.closeQuietly(os);
                IOUtils.closeQuietly(dis);
                IOUtils.closeQuietly(dos);
                if (null != client) {
                    client.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 定时发送心跳包到服务器，心跳发送失败会结束所有进程并退出程序
     * 通过心跳机制，来互相确认是否在线
     * @param dos DataOutputStream
     */
    private static void manualKeepAlive(DataOutputStream dos) {

        final int t_ttl = 30;
        // 刷新值
        KeepAliveTask keepAliveTask = new KeepAliveTask(() -> {
            // 刷新值
            try {
                JSONObject body = new JSONObject();
                body.put("ep_id", EP_ID);
                String content = "啦啦啦啦啦";
                body.put("content", content);
                body.put("time", LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS")));
                Message message = new Message(body.toJSONString(), MessageEnum.CONNECT);
                String request = message.toJsonString();
                log.info("发送心跳包到服务器：" + request);
                dos.write((request + nettyProperties.getDelimiterStr()).getBytes(StandardCharsets.UTF_8));
            } catch (Exception e) {
                Thread.currentThread().interrupt();
                e.printStackTrace();
            }
        }, t_ttl, "客户端定时向服务器发送心跳包");
        keepAliveTask.start();
    }

    /**
     * 消息处理
     *
     * @param strtmp 消息文本
     */
    public static void handleMessage(String strtmp) {
        if (StringUtils.isNotEmpty(strtmp)) {
            // 获取消息实例中的消息体
            String[] ret = strtmp.split(nettyProperties.getDelimiterStr());
            Message msg = new Message(ret[0]);
            // 对不同消息类型进行处理
            MessageEnum type = MessageEnum.getStructureEnum(msg);
            switch (Objects.requireNonNull(type)) {
                case CONNECT:
                    // TODO 心跳消息处理
                    log.info("收到来自服务器的心跳包信息：{}", msg.getBody());
                    break;
                case STATE:
                    // TODO 设备状态
                    log.info("收到来自服务器的数据信息：{}", msg.getBody());
                    break;
                default:
                    log.info(type.content + "消息内容: " + msg.getBody());
                    break;
            }

        }
    }
}
